import { defineStore } from 'pinia'
import { ref } from 'vue'
import { marked } from 'marked'

// 知识图谱数据结构接口
interface KnowledgeGraph {
  metadata: {
    version: string
    created: string
    description: string
    total_levels: number
    total_topics: number
    total_subtopics: number
    total_knowledge_points: number
    total_concepts: number
    total_quizzes: number
    total_students: number
  }
  levels: any[]
  topics: any[]
  subtopics: any[]
  knowledge_points: any[]
  concepts: any[]
  quizzes: any[]
  students: any[]
  assessments: any[]
  learning_paths: any[]
  relationships: any[]
}

// Neo4j 配置接口
interface Neo4jConfig {
  uri: string
  username: string
  password: string
}

export const useConverterStore = defineStore('converter', () => {
  // 状态
  const knowledgeGraph = ref<KnowledgeGraph>({
    metadata: {
      version: '3.0',
      created: new Date().toISOString().split('T')[0],
      description: 'Vue.js学习知识图谱数据结构 - 四层架构支持个性化学习',
      total_levels: 0,
      total_topics: 0,
      total_subtopics: 0,
      total_knowledge_points: 0,
      total_concepts: 0,
      total_quizzes: 0,
      total_students: 0
    },
    levels: [],
    topics: [],
    subtopics: [],
    knowledge_points: [],
    concepts: [],
    quizzes: [],
    students: [],
    assessments: [],
    learning_paths: [],
    relationships: []
  })

  const isConverting = ref(false)
  const isImporting = ref(false)
  const conversionProgress = ref(0)
  const importProgress = ref(0)

  // 层级映射
  const levelMapping: Record<string, any> = {
    '1 前端技术.md': { id: 'basic', name: '基础层', order: 1 },
    '2 开发环境.md': { id: 'basic', name: '基础层', order: 1 },
    '3 过渡层.md': { id: 'intermediate', name: '进阶层', order: 2 },
    '4-Vue模板指令.md': { id: 'intermediate', name: '进阶层', order: 2 },
    '第1章_前端技术绪论.md': { id: 'basic', name: '基础层', order: 1 },
    '第1章_前端技术基础.md': { id: 'basic', name: '基础层', order: 1 }
  }

  // 难度映射已移至前端界面配置

  // 方法
  const generateId = (text: string): string => {
    return text.toLowerCase()
      .replace(/[^a-z0-9\u4e00-\u9fa5]/g, '-')
      .replace(/-+/g, '-')
      .replace(/^-|-$/g, '')
  }

  const generateTopicId = (fileName: string): string => {
    const idMapping: Record<string, string> = {
      '1 前端技术.md': 'frontend-basics',
      '2 开发环境.md': 'development-environment',
      '3 过渡层.md': 'vue-transition',
      '4-Vue模板指令.md': 'vue-template-directives',
      '第1章_前端技术绪论.md': 'frontend-introduction',
      '第1章_前端技术基础.md': 'frontend-technology-basics'
    }
    return idMapping[fileName] || fileName.replace(/\s+/g, '-').replace('.md', '').toLowerCase()
  }

  const extractTopicName = (tokens: any[]): string => {
    const firstHeading = tokens.find(token => token.type === 'heading' && token.depth === 1)
    if (firstHeading) {
      return firstHeading.text.replace(/^\d+\s*/, '').trim()
    }
    return '未命名知识点'
  }

  const parseMarkdownContent = (content: string, fileName: string, dynamicLevelMapping: Record<string, any>) => {
    const lines = content.split('\n')
    const levelInfo = dynamicLevelMapping[fileName]
    if (!levelInfo) return

    let currentTopic: any = null
    let currentSubtopic: any = null
    let currentKnowledgePoint: any = null
    let currentConcept: any = null
    let contentBuffer: string[] = []

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i].trim()

      if (line.startsWith('# ')) {
        // 第1层级：Topic
        saveCurrentContent(currentConcept || currentKnowledgePoint, contentBuffer)
        contentBuffer = []

        const topicName = line.substring(2).trim().replace(/^\d+\s*/, '').trim()
        currentTopic = knowledgeGraph.value.topics.find(t => t.name === topicName)
        currentSubtopic = null
        currentKnowledgePoint = null
        currentConcept = null

      } else if (line.startsWith('## ')) {
        // 第2层级：Subtopic
        saveCurrentContent(currentConcept || currentKnowledgePoint, contentBuffer)
        contentBuffer = []

        if (currentTopic) {
          const subtopicName = line.substring(3).trim()
          const subtopicId = `${currentTopic.id}-${generateId(subtopicName)}`

          currentSubtopic = {
            id: subtopicId,
            name: subtopicName,
            topic_id: currentTopic.id,
            description: '',
            content: '',
            key_points: [],
            difficulty: 'beginner'
          }

          knowledgeGraph.value.subtopics.push(currentSubtopic)

          // 创建关系
          knowledgeGraph.value.relationships.push({
            type: 'PART_OF',
            from_id: subtopicId,
            to_id: currentTopic.id,
            fromLabel: 'Subtopic',
            toLabel: 'Topic'
          })
        }
        currentKnowledgePoint = null
        currentConcept = null

      } else if (line.startsWith('### ')) {
        // 第3层级：KnowledgePoint
        saveCurrentContent(currentConcept || currentKnowledgePoint, contentBuffer)
        contentBuffer = []

        if (currentSubtopic) {
          const knowledgePointName = line.substring(4).trim()
          const knowledgePointId = `${currentSubtopic.id}-kp-${generateId(knowledgePointName)}`

          currentKnowledgePoint = {
            id: knowledgePointId,
            name: knowledgePointName,
            subtopic_id: currentSubtopic.id,
            description: '',
            content: '',
            key_points: [],
            examples: [],
            difficulty: 'beginner'
          }

          knowledgeGraph.value.knowledge_points.push(currentKnowledgePoint)

          // 添加知识点与子主题的关系
          knowledgeGraph.value.relationships.push({
            type: 'PART_OF',
            from_id: knowledgePointId,
            to_id: currentSubtopic.id,
            fromLabel: 'KnowledgePoint',
            toLabel: 'Subtopic'
          })
        }
        currentConcept = null

      } else if (line.startsWith('#### ')) {
        // 第4层级 - Concept
        saveCurrentContent(currentConcept, contentBuffer)
        contentBuffer = []

        const conceptName = line.substring(5).trim()
        const conceptId = currentKnowledgePoint ?
          `${currentKnowledgePoint.id}-concept-${generateId(conceptName)}` :
          `concept-${generateId(conceptName)}`

        currentConcept = {
          id: conceptId,
          name: conceptName,
          knowledge_point_id: currentKnowledgePoint ? currentKnowledgePoint.id : null,
          definition: '',
          content: '',
          key_points: [],
          examples: [],
          related_concepts: [],
          difficulty: 'beginner'
        }

        knowledgeGraph.value.concepts.push(currentConcept)

        // 添加概念与知识点的关系
        if (currentKnowledgePoint) {
          knowledgeGraph.value.relationships.push({
            type: 'PART_OF',
            from_id: conceptId,
            to_id: currentKnowledgePoint.id,
            fromLabel: 'Concept',
            toLabel: 'KnowledgePoint'
          })
        }

      } else if (line.startsWith('- ') || line.startsWith('* ')) {
        // 列表项 - 添加到当前概念的关键点
        const listItem = line.substring(2).trim()
        if (listItem.length > 0) {
          if (currentConcept) {
            currentConcept.key_points.push(listItem)
          } else if (currentKnowledgePoint) {
            currentKnowledgePoint.key_points.push(listItem)
          }
        }

      } else if (line.length > 0) {
        // 收集内容
        contentBuffer.push(line)
      }
    }

    // 保存最后的内容
    if (currentConcept) {
      saveCurrentContent(currentConcept, contentBuffer)
    } else {
      saveCurrentContent(currentKnowledgePoint, contentBuffer)
    }
  }

  const saveCurrentContent = (item: any, contentBuffer: string[]) => {
    if (item && contentBuffer.length > 0) {
      const content = contentBuffer.join('\n').trim()
      item.content = content

      // 如果有 description 字段，也设置它
      if (item.hasOwnProperty('description')) {
        item.description = content.substring(0, 200) + (content.length > 200 ? '...' : '')
      }

      // 如果是概念，设置definition
      if (item.hasOwnProperty('definition')) {
        item.definition = content
      }
    }
  }

  const extractTopicFromTokens = (tokens: any[], fileName: string, dynamicLevelMapping: Record<string, any>, difficultyLevel: number = 1) => {
    const levelInfo = dynamicLevelMapping[fileName]
    if (!levelInfo) {
      console.warn(`未找到文件 ${fileName} 的层级映射`)
      return null
    }

    const topicId = generateTopicId(fileName)
    const topic = {
      id: topicId,
      name: extractTopicName(tokens),
      level_id: levelInfo.id,
      difficulty: getDifficultyFromFileName(fileName, difficultyLevel),
      description: extractDescription(tokens),
      prerequisites: extractPrerequisites(fileName),
      estimated_hours: estimateHours(tokens),
      status: 'to-learn',
      lastLearned: null,
      completionRate: 0,
      resources: [{
        id: `resource_${topicId}`,
        type: 'markdown',
        title: extractTopicName(tokens),
        path: fileName,
        section: '全文',
        completionRequired: true,
        status: 'available'
      }]
    }

    return topic
  }

  const extractDescription = (tokens: any[]): string => {
    const firstParagraph = tokens.find(token => token.type === 'paragraph')
    if (firstParagraph) {
      return firstParagraph.text.substring(0, 200) + (firstParagraph.text.length > 200 ? '...' : '')
    }
    return ''
  }

  const getDifficultyFromFileName = (fileName: string, defaultDifficulty: number = 1): number => {
    return defaultDifficulty
  }

  const extractPrerequisites = (fileName: string): string[] => {
    const prerequisites: Record<string, string[]> = {
      '1 前端技术.md': [],
      '2 开发环境.md': ['frontend-basics'],
      '3 过渡层.md': ['frontend-basics', 'development-environment'],
      '4-Vue模板指令.md': ['vue-transition'],
      '第1章_前端技术绪论.md': [],
      '第1章_前端技术基础.md': []
    }
    return prerequisites[fileName] || []
  }

  const estimateHours = (tokens: any[]): number => {
    const textLength = tokens
      .filter(token => token.type === 'paragraph' || token.type === 'text')
      .reduce((total, token) => total + (token.text ? token.text.length : 0), 0)

    return Math.max(1, Math.round(textLength / 1000 * 0.25))
  }

  const initializeLevels = () => {
    const levels = [
      {
        id: 'basic',
        name: '基础层',
        order: 1,
        description: '前端基础概念、开发环境配置',
        color: '#4CAF50'
      },
      {
        id: 'intermediate',
        name: '过渡层',
        order: 2,
        description: 'Vue框架入门、基础语法',
        color: '#2196F3'
      },
      {
        id: 'advanced',
        name: '进阶层',
        order: 3,
        description: 'Vue框架核心概念、模板语法',
        color: '#FF9800'
      },
      {
        id: 'expert',
        name: '高阶层',
        order: 4,
        description: '组件开发、路由管理、项目实战',
        color: '#F44336'
      }
    ]

    knowledgeGraph.value.levels = levels
    knowledgeGraph.value.metadata.total_levels = levels.length
  }

  // 动态生成层级映射
  const generateLevelMapping = (files: File[], selectedLevel: string): Record<string, any> => {
    const levelInfo = {
      basic: { id: 'basic', name: '基础层', order: 1, description: '前端基础概念、开发环境配置' },
      intermediate: { id: 'intermediate', name: '过渡层', order: 2, description: 'Vue框架入门、基础语法' },
      advanced: { id: 'advanced', name: '进阶层', order: 3, description: 'Vue框架核心概念、模板语法' },
      expert: { id: 'expert', name: '高阶层', order: 4, description: '组件开发、路由管理、项目实战' }
    }
    
    const mapping: Record<string, any> = {}
    files.forEach(file => {
      mapping[file.name] = levelInfo[selectedLevel as keyof typeof levelInfo] || levelInfo.basic
    })
    
    return mapping
  }

  // 转换文件
  const convertFiles = async (files: File[], selectedLevel: string = 'basic', difficultyLevel: number = 1) => {
    isConverting.value = true
    conversionProgress.value = 0

    try {
      // 生成动态层级映射
      const dynamicLevelMapping = generateLevelMapping(files, selectedLevel)
      
      // 重置知识图谱
      knowledgeGraph.value = {
        metadata: {
          version: '3.0',
          created: new Date().toISOString().split('T')[0],
          description: 'Vue.js学习知识图谱数据结构 - 四层架构支持个性化学习',
          total_levels: 0,
          total_topics: 0,
          total_subtopics: 0,
          total_knowledge_points: 0,
          total_concepts: 0,
          total_quizzes: 0,
          total_students: 0
        },
        levels: [],
        topics: [],
        subtopics: [],
        knowledge_points: [],
        concepts: [],
        quizzes: [],
        students: [],
        assessments: [],
        learning_paths: [],
        relationships: []
      }

      // 初始化层级
      initializeLevels()

      // 处理每个文件
      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        const content = await file.text()
        const tokens = marked.lexer(content)

        console.log(`正在解析文件: ${file.name}`)

        const topic = extractTopicFromTokens(tokens, file.name, dynamicLevelMapping, difficultyLevel)
        if (topic) {
          knowledgeGraph.value.topics.push(topic)
          console.log(`成功提取知识点: ${topic.name}`)
        }

        // 解析四层架构内容
        parseMarkdownContent(content, file.name, dynamicLevelMapping)

        conversionProgress.value = ((i + 1) / files.length) * 100
      }

      // 更新元数据
      knowledgeGraph.value.metadata.total_topics = knowledgeGraph.value.topics.length
      knowledgeGraph.value.metadata.total_subtopics = knowledgeGraph.value.subtopics.length
      knowledgeGraph.value.metadata.total_knowledge_points = knowledgeGraph.value.knowledge_points.length
      knowledgeGraph.value.metadata.total_concepts = knowledgeGraph.value.concepts.length

      return knowledgeGraph.value
    } catch (error) {
      console.error('转换失败:', error)
      throw error
    } finally {
      isConverting.value = false
    }
  }

  // 导入到 Neo4j
  const importToNeo4j = async (data: KnowledgeGraph, config: Neo4jConfig, importMode: string = 'incremental') => {
    isImporting.value = true
    importProgress.value = 0

    try {
      console.log('开始导入到 Neo4j...', config)
      console.log('前端传递的importMode:', importMode)
      console.log('importMode类型:', typeof importMode)
      
      // 准备导入数据
      const importData = {
        knowledgeGraph: data,
        neo4jConfig: {
          uri: config.uri,
          username: config.username,
          password: config.password
        },
        importMode: importMode
      }
      
      console.log('发送到后端的数据:', { ...importData, neo4jConfig: { ...importData.neo4jConfig, password: '***' } })
      
      // 调用后端API进行导入
      const response = await fetch('/api/neo4j/import', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(importData)
      })
      
      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.message || `HTTP error! status: ${response.status}`)
      }
      
      // 检查是否支持流式响应来显示进度
      const contentType = response.headers.get('content-type')
      if (contentType && contentType.includes('application/x-ndjson')) {
        // 处理流式响应以显示实时进度
        const reader = response.body?.getReader()
        const decoder = new TextDecoder()
        let buffer = ''
        
        if (reader) {
          while (true) {
            const { done, value } = await reader.read()
            if (done) break
            
            buffer += decoder.decode(value, { stream: true })
            const lines = buffer.split('\n')
            buffer = lines.pop() || ''
            
            for (const line of lines) {
              if (line.trim()) {
                try {
                  const progressData = JSON.parse(line)
                  if (progressData.progress !== undefined) {
                    importProgress.value = progressData.progress
                  }
                } catch (e) {
                  console.warn('解析进度数据失败:', e)
                }
              }
            }
          }
        }
      } else {
        // 模拟进度更新
        const progressInterval = setInterval(() => {
          if (importProgress.value < 90) {
            importProgress.value += 10
          }
        }, 500)
        
        // 等待响应完成并获取结果
        const result = await response.json()
        clearInterval(progressInterval)
        importProgress.value = 100
        
        return {
          success: true,
          message: result.message || '数据已成功导入到 Neo4j 数据库',
          statistics: result.statistics || {
            topics: data.topics.length,
            subtopics: data.subtopics.length,
            knowledge_points: data.knowledge_points.length,
            concepts: data.concepts.length,
            relationships: data.relationships.length
          }
        }
      }
    } catch (error) {
      console.error('导入失败:', error)
      
      // 如果是网络错误或API不存在，提供友好的错误信息
      if (error instanceof TypeError && error.message.includes('fetch')) {
        throw new Error('无法连接到后端服务，请确保后端API服务正在运行')
      }
      
      throw error
    } finally {
      isImporting.value = false
    }
  }

  return {
    // 状态
    knowledgeGraph,
    isConverting,
    isImporting,
    conversionProgress,
    importProgress,
    
    // 方法
    convertFiles,
    importToNeo4j
  }
})